<?php

namespace App\Models\Review;

use DateTimeInterface;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use SimpleXMLElement;

class ActivityModel extends Model
{
    use HasFactory;
    protected $connection="review";
    protected $table="tbl_activitys";
    protected $guarded=[];
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
    public static function makeFromXml($file){
        $path=base_path("xmltool/activity/{$file}");
        if(!file_exists($path)){
            throw new Exception("File Not Found");
        }
        $root=simplexml_load_file($path);
        // $nodes=[];
        // $items=self::parseChilds($root,$nodes);
        // return json_encode($items);
        $property=$root->xpath("property");
        $elements=$property[0];
        $tableName=$root->getName();
        $str=$tableName."\r\n";
        foreach($elements as $k=>$v){
            $str.=" > {$k}[";
            $i=0;
            foreach($v->attributes() as $a1=>$a2){
                $str.=($i++==0?'':' ')."{$a1}='{$a2}'";
            }
            $str.="]\r\n";
            foreach($v as $k1=>$v1){
                $str.="   >>   {$k1} {$v1}[";
                $i=0;
                foreach($v1->attributes() as $a1=>$a2){
                 $str.=($i++==0?'':' ')."{$a1}='{$a2}'";
                }
                $str.="]";
            }
        }
        return $str;
    }
    private static function parseChilds(SimpleXMLElement $node,&$root){
        if($node->count()){
            foreach($node->children() as $k=>$v){
              $child=[
                "name"=>$k,
                "children"=>[],
                "attr"=>[]
              ];
              self::parseAttr($v,$child);
              self::parseChilds($v,$child);
              $root[]=$child;
            }
        }
        return $root;
    }
    private static function parseAttr(SimpleXMLElement $element,&$cur){
        $attr=$element->attributes();
        foreach($attr as $k=>$v){
            $cur['attr'][$k]=$v;
        }
        return;
    }

}
